<template>
  <div class="task-comparison">
    <!-- 页面头部 -->
    <div class="page-header">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/performance/result' }">性能测试</el-breadcrumb-item>
        <el-breadcrumb-item>任务对比</el-breadcrumb-item>
      </el-breadcrumb>
      <div class="header-content">
        <div class="header-title">
          <h1>任务性能对比分析</h1>
          <p>对比不同任务的性能指标，发现优化机会</p>
        </div>
        <div class="header-actions">
          <el-button type="primary" @click="returnToReportList" plain>
            <el-icon><Back /></el-icon>返回报告列表
          </el-button>
        </div>
      </div>
    </div>

    <!-- 任务选择区域 -->
    <el-card v-if="!comparisonResult" class="selection-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <el-icon><DataAnalysis /></el-icon>
          <span>选择对比任务</span>
        </div>
      </template>

      <!-- 搜索过滤 -->
      <div class="filter-section">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索任务名称"
              prefix-icon="Search"
              clearable
              @input="handleSearch"
            />
          </el-col>
          <el-col :span="6">
            <el-select v-model="statusFilter" placeholder="报告状态" clearable @change="handleSearch">
              <el-option label="全部" value="" />
              <el-option label="已完成" value="0" />
              <el-option label="执行中" value="1" />
              <el-option label="运行失败" value="99" />
            </el-select>
          </el-col>
          <el-col :span="8">
            <el-date-picker
              v-model="timeRange"
              type="datetimerange"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              @change="handleSearch"
            />
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="performComparison" :disabled="selectedTasks.length < 2">
              开始对比 ({{ selectedTasks.length }})
            </el-button>
          </el-col>
        </el-row>
      </div>

      <!-- 任务列表 -->
      <div class="task-list">
        <el-row :gutter="20">
          <el-col :span="8" v-for="report in filteredReports" :key="report.id">
            <div
              class="task-card"
              :class="{ 'selected': isSelected(report), 'disabled': !canSelect(report) }"
              @click="toggleSelection(report)"
            >
              <div class="task-header">
                <div class="task-info">
                  <h4>{{ report.reportName }}</h4>
                  <p class="task-name">{{ report.task?.taskName || '未知任务' }}</p>
                </div>
                <div class="task-status">
                  <el-tag
                    :type="getStatusType(report.reportStatus)"
                    size="small"
                  >
                    {{ getStatusText(report.reportStatus) }}
                  </el-tag>
                </div>
              </div>
              <div class="task-metrics">
                <div class="metric-item">
                  <span class="metric-label">TPS</span>
                  <span class="metric-value">{{ formatNumber(report.avgTps || 0, 2) }}</span>
                </div>
                <div class="metric-item">
                  <span class="metric-label">响应时间</span>
                  <span class="metric-value">{{ formatNumber(report.avgResponseTime || 0, 2) }}ms</span>
                </div>
                <div class="metric-item">
                  <span class="metric-label">成功率</span>
                  <span class="metric-value">{{ getSuccessRate(report) }}%</span>
                </div>
              </div>
              <div class="task-footer">
                <span class="executor">{{ report.executor || '未知' }}</span>
                <span class="time">{{ formatDate(report.create_time) }}</span>
              </div>
              <div class="selection-indicator" v-if="isSelected(report)">
                <el-icon><Check /></el-icon>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 选择提示 -->
      <div class="selection-hint">
        <el-alert
          :title="`已选择 ${selectedTasks.length} 个任务${selectedTasks.length < 2 ? '，至少需要选择2个任务进行对比' : selectedTasks.length > 5 ? '，最多支持5个任务对比' : ''}`"
          :type="selectedTasks.length < 2 ? 'warning' : selectedTasks.length > 5 ? 'error' : 'success'"
          :closable="false"
          show-icon
        />
      </div>
    </el-card>

    <!-- 对比结果 -->

    <div v-if="comparisonResult" class="comparison-result">
      <!-- 操作栏 -->
      <div class="result-actions">
        <el-button @click="resetComparison" icon="ArrowLeft">重新选择</el-button>
        <el-button type="success" @click="exportReport" icon="Download">导出报告</el-button>
      </div>

      <!-- 对比概览 -->
      <el-card class="overview-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <el-icon><PieChart /></el-icon>
            <span>对比概览</span>
          </div>
        </template>
        <el-row :gutter="20">
          <el-col :xs="24" :sm="24" :md="24 / Math.min(Object.keys(comparisonResult.task_info).length, 4)" 
                 v-for="(taskInfo, taskId) in comparisonResult.task_info" :key="taskId">
            <div class="overview-item" :class="{'no-data': !hasMetricsData(taskId)}">
              <h3>{{ taskInfo.task_name }}</h3>
              <div v-if="hasMetricsData(taskId)" class="overview-stats">
                <div class="stat-item">
                  <span class="stat-value">{{ formatNumber(comparisonResult.comparison_metrics[taskId]?.averages?.tps, 2) }}</span>
                  <span class="stat-label">平均TPS</span>
                </div>
                <div class="stat-item">
                  <span class="stat-value">{{ formatNumber(comparisonResult.comparison_metrics[taskId]?.averages?.response_time, 2) }}ms</span>
                  <span class="stat-label">响应时间</span>
                </div>
                <div class="stat-item">
                  <span class="stat-value">{{ formatNumber(comparisonResult.comparison_metrics[taskId]?.averages?.error_rate, 2) }}%</span>
                  <span class="stat-label">错误率</span>
                </div>
              </div>
              <div v-else class="no-data-message">
                <el-icon><InfoFilled /></el-icon> 无可用数据
              </div>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 性能排名 -->
      <el-card class="ranking-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <el-icon><TrendCharts /></el-icon>
            <span>性能排名</span>
            <el-button v-if="Object.keys(comparisonResult.comparison_metrics).length < Object.keys(comparisonResult.task_info).length" 
                     type="warning" size="small" plain style="margin-left: 10px">
              部分任务数据不完整
            </el-button>
          </div>
        </template>
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="ranking-section">
              <h4>TPS排名</h4>
              <div class="ranking-list">
                <div
                  v-for="(item, index) in comparisonResult.rankings.tps"
                  :key="item.task_id"
                  class="ranking-item"
                >
                  <span class="rank">{{ index + 1 }}</span>
                  <span class="name">{{ item.task_name }}</span>
                  <span class="value">{{ formatNumber(item.value, 2) }}</span>
                </div>
                <div v-if="comparisonResult.rankings.tps.length === 0" class="no-ranking-data">
                  <el-icon><InfoFilled /></el-icon> 无排名数据
                </div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="ranking-section">
              <h4>响应时间排名</h4>
              <div class="ranking-list">
                <div
                  v-for="(item, index) in comparisonResult.rankings.response_time"
                  :key="item.task_id"
                  class="ranking-item"
                >
                  <span class="rank">{{ index + 1 }}</span>
                  <span class="name">{{ item.task_name }}</span>
                  <span class="value">{{ formatNumber(item.value, 2) }}ms</span>
                </div>
                <div v-if="comparisonResult.rankings.response_time.length === 0" class="no-ranking-data">
                  <el-icon><InfoFilled /></el-icon> 无排名数据
                </div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="ranking-section">
              <h4>错误率排名</h4>
              <div class="ranking-list">
                <div
                  v-for="(item, index) in comparisonResult.rankings.error_rate"
                  :key="item.task_id"
                  class="ranking-item"
                >
                  <span class="rank">{{ index + 1 }}</span>
                  <span class="name">{{ item.task_name }}</span>
                  <span class="value">{{ formatNumber(item.value, 2) }}%</span>
                </div>
                <div v-if="comparisonResult.rankings.error_rate.length === 0" class="no-ranking-data">
                  <el-icon><InfoFilled /></el-icon> 无排名数据
                </div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="ranking-section">
              <h4>稳定性排名</h4>
              <div class="ranking-list">
                <div
                  v-for="(item, index) in comparisonResult.rankings.stability"
                  :key="item.task_id"
                  class="ranking-item"
                >
                  <span class="rank">{{ index + 1 }}</span>
                  <span class="name">{{ item.task_name }}</span>
                  <span class="value">{{ formatNumber(item.value * 100, 2) }}%</span>
                </div>
                <div v-if="comparisonResult.rankings.stability.length === 0" class="no-ranking-data">
                  <el-icon><InfoFilled /></el-icon> 无排名数据
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 详细指标对比 -->
      <el-card class="metrics-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <el-icon><DataAnalysis /></el-icon>
            <span>详细指标对比</span>
          </div>
        </template>
        <el-table :data="metricsTableData" stripe height="350" border>
          <el-table-column prop="metric" label="指标" width="150" fixed="left" />
          <el-table-column
            v-for="(taskInfo, taskId) in comparisonResult.task_info"
            :key="taskId"
            :label="taskInfo.task_name"
            align="center"
          >
            <template #default="{ row }">
              <span
                :class="{ 'best-value': row.bestTaskId == taskId }"
                class="metric-cell"
              >
                {{ row.values[taskId] }}
              </span>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 性能趋势图表 -->
      <el-card class="charts-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <el-icon><TrendCharts /></el-icon>
            <span>性能趋势对比</span>
          </div>
        </template>
        <el-row :gutter="20">
          <el-col :span="12">
            <div ref="tpsChart" class="chart-container"></div>
          </el-col>
          <el-col :span="12">
            <div ref="responseTimeChart" class="chart-container"></div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 总结与建议 -->
      <el-card class="summary-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <el-icon><InfoFilled /></el-icon>
            <span>总结与建议</span>
          </div>
        </template>
        <div class="summary-content">
          <el-alert
            v-if="comparisonResult.summary?.best_performance_task"
            :title="comparisonResult.summary?.best_performance_task?.task_name + ' 表现最佳'"
            type="success"
            :closable="false"
          >
            <div class="summary-details">
              <p><strong>最佳性能指标:</strong></p>
              <ul>
                <li>平均TPS: {{ formatNumber(comparisonResult.summary.best_performance_task.avg_tps, 2) }}</li>
                <li>平均响应时间: {{ formatNumber(comparisonResult.summary.best_performance_task.avg_response_time, 2) }}ms</li>
              </ul>
              <p><strong>优化建议:</strong></p>
              <ul>
                <li v-for="suggestion in comparisonResult.summary.recommendations" :key="suggestion">
                  {{ suggestion }}
                </li>
              </ul>
            </div>
          </el-alert>
          <el-alert
            v-else
            title="无法确定最佳表现任务"
            type="info"
            :closable="false"
          >
            <div class="summary-details">
              <p>可能的原因:</p>
              <ul>
                <li>部分任务没有足够的性能数据</li>
                <li>任务性能指标不完整</li>
              </ul>
              <p>建议:</p>
              <ul>
                <li>选择有完整性能数据的任务进行对比</li>
                <li>确保任务已经执行完成并生成了性能报告</li>
              </ul>
            </div>
          </el-alert>
        </div>
      </el-card>
    </div>

    <!-- 加载遮罩 -->
    <div v-if="loading" class="loading-overlay">
      <el-icon class="is-loading"><Loading /></el-icon>
      <p>正在分析对比数据...</p>
    </div>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus'
import { mapState } from 'vuex'
import * as echarts from 'echarts'
import { 
  Search, DataAnalysis, View, Download, Delete,
  RefreshRight, Setting, Calendar, Check, Loading,
  TrendCharts, PieChart, InfoFilled, Back
} from '@element-plus/icons-vue'

export default {
  name: 'TaskComparison',
  components: {
    Search, DataAnalysis, View, Download, Delete,
    RefreshRight, Setting, Calendar, Check, Loading,
    TrendCharts, PieChart, InfoFilled, Back
  },
  data() {
    return {
      loading: false,
      searchKeyword: '',
      statusFilter: '',
      timeRange: [],
      reportList: [],
      selectedTasks: [],
      comparisonResult: null,
      
      // 分页
      currentPage: 1,
      pageSize: 12
    }
  },
  computed: {
    ...mapState({
      pro: state => state.pro
    }),
    
    filteredReports() {
      let filtered = this.reportList
      
      if (this.searchKeyword) {
        filtered = filtered.filter(report => 
          report.reportName?.toLowerCase().includes(this.searchKeyword.toLowerCase()) ||
          report.task?.taskName?.toLowerCase().includes(this.searchKeyword.toLowerCase())
        )
      }
      
      if (this.statusFilter) {
        filtered = filtered.filter(report => report.reportStatus === this.statusFilter)
      }
      
      return filtered
    },
    
    metricsTableData() {
      if (!this.comparisonResult?.comparison_metrics) return []
      
      const metrics = [
        { key: 'averages.tps', label: '平均TPS', format: (v) => v },
        { key: 'averages.response_time', label: '平均响应时间(ms)', format: (v) => v + 'ms' },
        { key: 'averages.error_rate', label: '错误率(%)', format: (v) => v + '%' },
        { key: 'extremes.max_tps', label: '最大TPS', format: (v) => v },
        { key: 'extremes.min_tps', label: '最小TPS', format: (v) => v },
        { key: 'totals.total_requests', label: '总请求数', format: (v) => v },
        { key: 'stability.tps_stability', label: 'TPS稳定性', format: (v) => (v * 100).toFixed(1) + '%' },
        { key: 'stability.response_time_stability', label: '响应时间稳定性', format: (v) => (v * 100).toFixed(1) + '%' }
      ]
      
      return metrics.map(metric => {
        const values = {}
        let bestValue = null
        let bestTaskId = null
        
        // 获取所有任务ID，包括可能没有指标数据的任务
        const allTaskIds = Object.keys(this.comparisonResult.task_info)
        
        // 先遍历所有任务ID，确保每个任务都有一个值（即使是'-'）
        allTaskIds.forEach(taskId => {
          // 如果任务没有指标数据，显示'-'
          if (!this.comparisonResult.comparison_metrics[taskId]) {
            values[taskId] = '-'
            return
          }
          
          const value = this.getNestedValue(this.comparisonResult.comparison_metrics[taskId], metric.key)
          values[taskId] = metric.format(value || 0)
          
          // 只有有效数据的任务才参与最佳值比较
          if (value !== null && value !== undefined) {
            if (bestValue === null) {
              bestValue = value
              bestTaskId = taskId
            } else {
              const isBetter = metric.key.includes('response_time') || metric.key.includes('error_rate') 
                ? value < bestValue 
                : value > bestValue
              if (isBetter) {
                bestValue = value
                bestTaskId = taskId
              }
            }
          }
        })
        
        return {
          metric: metric.label,
          values,
          bestTaskId
        }
      })
    }
  },
  
  async mounted() {
    await this.loadReports()
  },
  
  beforeUnmount() {
    // 移除窗口大小变化的事件监听器
    window.removeEventListener('resize', this.handleResize)
    
    // 销毁图表实例
    if (this.$refs.tpsChart) {
      echarts.getInstanceByDom(this.$refs.tpsChart)?.dispose()
    }
    if (this.$refs.responseTimeChart) {
      echarts.getInstanceByDom(this.$refs.responseTimeChart)?.dispose()
    }
  },
  
  methods: {
    async loadReports() {
      this.loading = true
      try {
        const params = {
          project_id: this.pro.id,
          page_size: 50  // 加载更多数据用于选择
        }
        
        const response = await this.$api.getTaskReports(params)
        this.reportList = response.data.result || response.data.data || []
      } catch (error) {
        ElMessage.error('加载报告列表失败: ' + (error.message || '未知错误'))
      } finally {
        this.loading = false
      }
    },
    
    handleSearch() {
      // 搜索逻辑已在computed中实现
    },
    
    isSelected(report) {
      return this.selectedTasks.some(task => task.id === report.id)
    },
    
    canSelect(report) {
      if (this.selectedTasks.length >= 5) return false
      
      // 检查是否已经选择了同一任务的其他报告
      const taskId = this.getTaskId(report)
      if (!taskId) return false
      
      return !this.selectedTasks.some(task => this.getTaskId(task) === taskId)
    },
    
    getTaskId(report) {
      return report.task?.id || report.taskId || report.task_id
    },
    
    toggleSelection(report) {
      if (!this.canSelect(report) && !this.isSelected(report)) return
      
      if (this.isSelected(report)) {
        this.selectedTasks = this.selectedTasks.filter(task => task.id !== report.id)
      } else {
        this.selectedTasks.push(report)
      }
    },
    
    async performComparison() {
      if (this.selectedTasks.length < 2) {
        ElMessage.warning('请至少选择2个任务进行对比')
        return
      }
      
      this.loading = true
      try {
        // 获取任务ID，使用任务ID而不是报告ID
        const taskIds = this.selectedTasks.map(task => this.getTaskId(task))
        const params = {
          task_ids: [...new Set(taskIds)], // 去重
          time_range_hours: 72 // 增加时间范围，确保有足够的数据
        }
        
        console.log('对比参数:', params)
        
        const response = await this.$api.compareTaskPerformance(params)
        this.comparisonResult = response.data.comparison_report
        
        console.log('对比结果完整数据:', JSON.stringify(this.comparisonResult))
        console.log('任务信息:', this.comparisonResult.task_info)
        console.log('对比指标:', this.comparisonResult.comparison_metrics)
        console.log('排名数据:', this.comparisonResult.rankings)
        console.log('时间线数据:', this.comparisonResult.timeline_data)
        
        // 检查是否有任务没有数据
        const noDataTasks = []
        Object.keys(this.comparisonResult.task_info).forEach(taskId => {
          if (!this.comparisonResult.comparison_metrics[taskId]) {
            noDataTasks.push(this.comparisonResult.task_info[taskId].task_name)
          }
        })
        
        if (noDataTasks.length > 0) {
          ElMessage.warning(`以下任务没有足够的性能数据: ${noDataTasks.join(', ')}`)
        }
        
        // 渲染图表
        this.$nextTick(() => {
          this.renderCharts()
        })
        
        ElMessage.success('对比分析完成')
      } catch (error) {
        ElMessage.error('对比分析失败: ' + (error.message || '未知错误'))
        console.error('对比分析错误:', error)
      } finally {
        this.loading = false
      }
    },
    
    renderCharts() {
      this.renderTpsChart()
      this.renderResponseTimeChart()
      
      // 添加窗口大小变化时重新渲染图表
      window.addEventListener('resize', this.handleResize)
    },
    
    // 添加处理窗口大小变化的方法
    handleResize() {
      if (this.$refs.tpsChart && this.$refs.responseTimeChart) {
        echarts.getInstanceByDom(this.$refs.tpsChart)?.resize()
        echarts.getInstanceByDom(this.$refs.responseTimeChart)?.resize()
      }
    },
    
    renderTpsChart() {
      if (!this.$refs.tpsChart) {
        console.warn('TPS图表DOM元素不存在')
        return
      }
      
      const chart = echarts.init(this.$refs.tpsChart)
      const option = {
        title: { text: 'TPS对比', left: 'center' },
        tooltip: { trigger: 'axis' },
        legend: { bottom: 0 },
        xAxis: { type: 'category', data: [] },
        yAxis: { type: 'value', name: 'TPS' },
        series: [],
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          top: '15%',
          containLabel: true
        }
      }
      
      let hasData = false
      let commonTimePoints = []
      
      // 确保所有任务都有数据点
      if (this.comparisonResult?.timeline_data) {
        console.log('渲染TPS图表，时间线数据:', this.comparisonResult.timeline_data)
        
        // 获取所有任务ID，包括可能没有指标数据的任务
        const allTaskIds = Object.keys(this.comparisonResult.task_info)
        console.log('所有任务ID:', allTaskIds)
        
        // 首先收集所有有效的时间点
        allTaskIds.forEach(taskId => {
          if (!this.comparisonResult.timeline_data[taskId]) {
            console.log(`任务 ${taskId} 没有时间线数据`)
            return
          }
          
          const timeline = this.comparisonResult.timeline_data[taskId]
          if (timeline && timeline.length > 0) {
            console.log(`任务 ${taskId} 有 ${timeline.length} 个时间点`)
            if (commonTimePoints.length === 0) {
              commonTimePoints = timeline.map(point => point.time)
            }
          }
        })
        
        // 如果有时间点，设置X轴数据
        if (commonTimePoints.length > 0) {
          option.xAxis.data = commonTimePoints.map(time => new Date(time).toLocaleTimeString())
        }
        
        // 然后为每个任务添加数据系列
        allTaskIds.forEach(taskId => {
          const taskName = this.comparisonResult.task_info[taskId]?.task_name || `任务${taskId}`
          
          if (!this.comparisonResult.timeline_data[taskId]) {
            // 如果没有时间线数据，添加空系列
            option.series.push({
              name: taskName,
              type: 'line',
              data: [],
              smooth: true,
              showSymbol: false,
              lineStyle: {
                width: 3
              }
            })
            return
          }
          
          const timeline = this.comparisonResult.timeline_data[taskId]
          
          if (timeline && timeline.length > 0) {
            hasData = true
            
            option.series.push({
              name: taskName,
              type: 'line',
              data: timeline.map(point => point.tps),
              smooth: true,
              showSymbol: false,
              lineStyle: {
                width: 3
              }
            })
          } else {
            // 即使没有数据，也添加一个空系列，保持图例的一致性
            option.series.push({
              name: taskName,
              type: 'line',
              data: [],
              smooth: true,
              showSymbol: false,
              lineStyle: {
                width: 3
              }
            })
          }
        })
      }
      
      // 如果没有数据，显示无数据提示
      if (!hasData) {
        option.title.text = 'TPS对比 (无数据)'
      }
      
      console.log('TPS图表配置:', option)
      chart.setOption(option)
    },
    
    renderResponseTimeChart() {
      if (!this.$refs.responseTimeChart) {
        console.warn('响应时间图表DOM元素不存在')
        return
      }
      
      const chart = echarts.init(this.$refs.responseTimeChart)
      const option = {
        title: { text: '响应时间对比', left: 'center' },
        tooltip: { trigger: 'axis' },
        legend: { bottom: 0 },
        xAxis: { type: 'category', data: [] },
        yAxis: { type: 'value', name: '响应时间(ms)' },
        series: [],
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          top: '15%',
          containLabel: true
        }
      }
      
      let hasData = false
      let commonTimePoints = []
      
      if (this.comparisonResult?.timeline_data) {
        console.log('渲染响应时间图表，时间线数据:', this.comparisonResult.timeline_data)
        
        // 获取所有任务ID，包括可能没有指标数据的任务
        const allTaskIds = Object.keys(this.comparisonResult.task_info)
        
        // 首先收集所有有效的时间点
        allTaskIds.forEach(taskId => {
          if (!this.comparisonResult.timeline_data[taskId]) {
            console.log(`任务 ${taskId} 没有时间线数据`)
            return
          }
          
          const timeline = this.comparisonResult.timeline_data[taskId]
          if (timeline && timeline.length > 0) {
            console.log(`任务 ${taskId} 有 ${timeline.length} 个时间点`)
            if (commonTimePoints.length === 0) {
              commonTimePoints = timeline.map(point => point.time)
            }
          }
        })
        
        // 如果有时间点，设置X轴数据
        if (commonTimePoints.length > 0) {
          option.xAxis.data = commonTimePoints.map(time => new Date(time).toLocaleTimeString())
        }
        
        // 然后为每个任务添加数据系列
        allTaskIds.forEach(taskId => {
          const taskName = this.comparisonResult.task_info[taskId]?.task_name || `任务${taskId}`
          
          if (!this.comparisonResult.timeline_data[taskId]) {
            // 如果没有时间线数据，添加空系列
            option.series.push({
              name: taskName,
              type: 'line',
              data: [],
              smooth: true,
              showSymbol: false,
              lineStyle: {
                width: 3
              }
            })
            return
          }
          
          const timeline = this.comparisonResult.timeline_data[taskId]
          
          if (timeline && timeline.length > 0) {
            hasData = true
            
            option.series.push({
              name: taskName,
              type: 'line',
              data: timeline.map(point => point.response_time),
              smooth: true,
              showSymbol: false,
              lineStyle: {
                width: 3
              }
            })
          } else {
            // 即使没有数据，也添加一个空系列，保持图例的一致性
            option.series.push({
              name: taskName,
              type: 'line',
              data: [],
              smooth: true,
              showSymbol: false,
              lineStyle: {
                width: 3
              }
            })
          }
        })
      }
      
      // 如果没有数据，显示无数据提示
      if (!hasData) {
        option.title.text = '响应时间对比 (无数据)'
      }
      
      console.log('响应时间图表配置:', option)
      chart.setOption(option)
    },
    
    resetComparison() {
      this.comparisonResult = null
      this.selectedTasks = []
    },
    
    exportReport() {
      // 导出功能实现
      ElMessage.info('导出功能开发中...')
    },
    
    returnToReportList() {
      window.history.back();
    },
    
    getStatusType(status) {
      const statusMap = {
        '0': 'success',
        '1': 'warning', 
        '99': 'danger'
      }
      return statusMap[status] || 'info'
    },
    
    getStatusText(status) {
      const statusMap = {
        '0': '已完成',
        '1': '执行中',
        '99': '运行失败'
      }
      return statusMap[status] || '未知'
    },
    
    getSuccessRate(report) {
      if (!report.totalRequests || report.totalRequests === 0) return 0
      return ((report.successRequests || 0) / report.totalRequests * 100).toFixed(1)
    },
    
    formatDate(dateStr) {
      if (!dateStr) return '-'
      return new Date(dateStr).toLocaleString()
    },
    
    formatNumber(value, precision = 2) {
      if (value === null || value === undefined) return '-'
      return value.toFixed(precision)
    },
    
    getNestedValue(obj, path) {
      return path.split('.').reduce((current, key) => current?.[key], obj)
    },

    hasMetricsData(taskId) {
      return this.comparisonResult?.comparison_metrics?.[taskId]?.averages !== undefined;
    }
  }
}
</script>

<style scoped lang="scss">
.task-comparison {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
  
  // 确保内容不会超出容器
  overflow-x: hidden;
  padding-bottom: 100px; // 增加底部间距到100px
}

.page-header {
  margin-bottom: 24px;
  
  h1 {
    margin: 10px 0;
    color: #303133;
  }
  
  p {
    color: #909399;
    margin: 0;
  }
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.header-title {
  flex: 1;
}

.header-actions {
  margin-left: 20px;
}

.selection-card {
  margin-bottom: 24px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
}

.filter-section {
  margin-bottom: 20px;
}

.task-list {
  margin-bottom: 20px;
}

.task-card {
  border: 2px solid #e4e7ed;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  cursor: pointer;
  transition: all 0.3s;
  position: relative;
  background: white;
  
  &:hover {
    border-color: #409eff;
    box-shadow: 0 2px 12px rgba(64, 158, 255, 0.1);
  }
  
  &.selected {
    border-color: #409eff;
    background: #f0f9ff;
  }
  
  &.disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }
}

.task-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
  
  h4 {
    margin: 0;
    color: #303133;
    font-size: 16px;
  }
  
  .task-name {
    margin: 4px 0 0 0;
    color: #909399;
    font-size: 12px;
  }
}

.task-metrics {
  display: flex;
  gap: 16px;
  margin-bottom: 12px;
}

.metric-item {
  display: flex;
  flex-direction: column;
  
  .metric-label {
    font-size: 12px;
    color: #909399;
  }
  
  .metric-value {
    font-size: 14px;
    font-weight: 500;
    color: #303133;
  }
}

.task-footer {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #909399;
}

.selection-indicator {
  position: absolute;
  top: 8px;
  right: 8px;
  width: 24px;
  height: 24px;
  background: #409eff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.selection-hint {
  margin-top: 16px;
}

.comparison-result {
  .result-actions {
    margin-bottom: 20px;
    display: flex;
    gap: 12px;
  }
   
  // 添加滚动区域样式
  max-height: calc(100vh - 200px);
  overflow-y: auto;
  padding-right: 10px; // 添加右侧padding，避免滚动条贴边
  padding-bottom: 40px; // 添加底部padding，确保内容完全显示
}

.overview-card,
.ranking-card,
.metrics-card,
.charts-card,
.summary-card {
  margin-bottom: 24px;
}

.overview-item {
  text-align: center;
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background: white;
  
  h3 {
    margin: 0 0 16px 0;
    color: #303133;
  }
  
  &.no-data {
    background: #f8f9fa;
    border: 1px dashed #e4e7ed;
  }
}

.overview-stats {
  display: flex;
  justify-content: space-around;
}

.stat-item {
  display: flex;
  flex-direction: column;
  
  .stat-value {
    font-size: 20px;
    font-weight: 600;
    color: #409eff;
  }
  
  .stat-label {
    font-size: 12px;
    color: #909399;
    margin-top: 4px;
  }
}

.ranking-section {
  h4 {
    margin: 0 0 12px 0;
    color: #303133;
  }
}

.ranking-list {
  background: #f8f9fa;
  border-radius: 6px;
  padding: 12px;
}

.ranking-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 0;
  border-bottom: 1px solid #e4e7ed;
  
  &:last-child {
    border-bottom: none;
  }
  
  .rank {
    width: 20px;
    height: 20px;
    border-radius: 50%;
    background: #409eff;
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    font-weight: 500;
  }
  
  .name {
    flex: 1;
    font-size: 14px;
  }
  
  .value {
    font-weight: 500;
    color: #409eff;
  }
}

.metric-cell {
  &.best-value {
    color: #67c23a;
    font-weight: 600;
  }
}

.chart-container {
  height: 300px;
  margin-bottom: 20px; // 添加底部间距
}

.summary-details {
  ul {
    margin: 8px 0;
    padding-left: 20px;
  }
  
  li {
    margin: 4px 0;
  }
}

.summary-content {
  max-height: 300px; /* 设置最大高度 */
  overflow-y: auto; /* 添加滚动条 */
  padding-right: 5px; /* 添加右侧内边距，避免滚动条贴边 */
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.9);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 2000;
  
  .el-icon {
    font-size: 32px;
    color: #409eff;
    margin-bottom: 12px;
  }
  
  p {
    color: #409eff;
    font-size: 14px;
  }
}

.no-data-message {
  font-size: 12px;
  color: #909399;
  margin-top: 10px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.no-ranking-data {
  font-size: 12px;
  color: #909399;
  margin-top: 10px;
  display: flex;
  align-items: center;
  gap: 4px;
}

// 添加响应式布局样式
@media screen and (max-width: 768px) {
  .ranking-card .el-row {
    display: flex;
    flex-direction: column;
    
    .el-col {
      width: 100%;
      margin-bottom: 16px;
    }
  }
  
  .charts-card .el-row {
    display: flex;
    flex-direction: column;
    
    .el-col {
      width: 100%;
      margin-bottom: 16px;
    }
  }
  
  .chart-container {
    height: 250px; // 在小屏幕上减小图表高度
  }
}
</style>